package com.bsoft.gol.editor.fileUpload;


import ctd.util.context.Context;
import ctd.util.context.ContextUtils;
import com.bsoft.gol.editor.model.ImportResult;

import java.util.Map;

public abstract class AbstractTranslator<X extends AbstractInExcel, D extends AbstractHolder> implements Translator<X, D> {

    @Override
    public abstract void preTranslate(TableData<X> tableData);

    @Override
    public TableData<D> translate(TableData<X> tableData) {
        preTranslate(tableData);
        TableData<D> translatedTableData = postTranslate(tableData);
        afterTranslate(translatedTableData);
        return translatedTableData;
    }

    @Override
    public abstract TableData<D> postTranslate(TableData<X> tableData);

    @Override
    public abstract void afterTranslate(TableData<D> tableData);


    @Override
    public ImportResult reverse(TableData<D> tableData, TableData<X> tableDataOri) {
        int size = tableData.getRowData().size();
        for (int j = 0; j < size; j++) {
            D d = tableData.getRowData().get(j);
            X x = tableDataOri.getRowData().get(j);
            if (d.isValid()) {//失败的就存进日志
                continue;
            }
            if (d.getErrorMsg().length() > 0) {
                String error = d.getErrorMsg().toString();
                error = error.startsWith(ErrorTipConst.SPLIT_CHAR) ? error.substring(1) : error;
                x.setInvalidMsg(error);
            }
            d = null;
        }
        if (tableDataOri.getInvalidCount().get() < tableData.getInvalidCount().get()) {
            tableDataOri.setInvalidCount(tableData.getInvalidCount());
        }
        ImportResult result = new ImportResult();
        int total = tableData.getCount().get();
        int fail = tableDataOri.getInvalidCount().get();//转换和保存过程的未通过验证和数据报错错误有问题的数据的并集
        tableData = null;
        result.setFailCount(fail);
        result.setTotal(total);
        result.setSuccesCount(total - fail);
        return result;
    }

    public String getUserId() {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) ContextUtils.get(Context.RPC_INVOKE_HEADERS);
        String userId = "";
        if (map != null) {
            userId = (String) map.get(Context.UID);
        }
        return userId;
    }
}
